package com.linkhub.oms.data.sync.service.impl;

import com.linkhub.oms.common.enums.IEnumConvert;
import com.linkhub.oms.common.enums.mp.CustomerOrderStatusEnum;
import com.linkhub.oms.common.enums.mp.EmployeeOrderStatusEnum;
import com.linkhub.oms.common.enums.mp.OrderStatusEnum;
import com.linkhub.oms.common.enums.mp.TrackingNumberStatusEnum;
import com.linkhub.oms.dao.mpservice.IOrderService;
import com.linkhub.oms.data.sync.api.yunexpress.domain.request.GetTrackingNumberRequest;
import com.linkhub.oms.data.sync.api.yunexpress.domain.response.GetOrderResponse;
import com.linkhub.oms.data.sync.api.yunexpress.domain.response.GetTrackingNumberResponse;
import com.linkhub.oms.data.sync.enums.YunTuOrderStatusEnum;
import com.linkhub.oms.data.sync.service.OMSYunExpressApiService;
import com.linkhub.oms.data.sync.service.YunTuBizService;
import com.linkhub.oms.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: YunTuGetOrderStatusBizServiceImpl
 * @Author: Jaycle
 * @Date: 2024/6/30 10:02
 * @Version: 1.0
 */
@Slf4j
@Service
public class YunTuBizServiceImpl implements YunTuBizService {

    @Resource
    private OMSYunExpressApiService omsYunExpressApiService;

    @Resource
    private IOrderService orderService;

    @Override
    public void getOrderStatusJod() {
        List<OrderEntity> orderEntityList = orderService.getByOrderStatus(OrderStatusEnum.DELIVERED);
        for (OrderEntity orderEntity : orderEntityList) {
            String wayBillNumber = orderEntity.getWayBillNumber();
            if (StringUtils.isNotEmpty(wayBillNumber)) {
                GetOrderResponse getOrderResponse = omsYunExpressApiService.getOrder(wayBillNumber);
                if (getOrderResponse.success() && getOrderResponse.getItem() != null) {
                    int status = getOrderResponse.getItem().getStatus();
                    if (YunTuOrderStatusEnum.SIGNED.getCode().equals(status)) {
                        OrderEntity update = new OrderEntity();
                        update.setOrderStatus(OrderStatusEnum.HAVE_BEEN_SIGNED);
                        update.setEmployeeOrderStatus(EmployeeOrderStatusEnum.HAVE_BEEN_SIGNED);
                        orderService.updateOrderInfo(orderEntity.getSysOrderId(), update);
                    }
                }
            }
        }
    }

    @Override
    public void getTrackingNumberJod() {
        List<OrderEntity> orderEntityList = orderService.getNeedUpdateTrackingNUmber();
        List<String> batchGetTrackingNumber = generateSysOrderIdStrings(orderEntityList);
        for (String getTrackingNumberString : batchGetTrackingNumber) {
            GetTrackingNumberRequest getTrackingNumberRequest = new GetTrackingNumberRequest();
            getTrackingNumberRequest.setCustomerOrderNumber(getTrackingNumberString);
            GetTrackingNumberResponse getTrackingNumberResponse = omsYunExpressApiService.getTrackingNumber(getTrackingNumberRequest);

            List<GetTrackingNumberResponse.Item> getTrackingNumberResponseItems = getTrackingNumberResponse.getItems();
            if (getTrackingNumberResponse.success() && getTrackingNumberResponseItems != null) {
                for (GetTrackingNumberResponse.Item getTrackingNumberResponseItem : getTrackingNumberResponseItems) {
                    final String customerOrderNumber = getTrackingNumberResponseItem.getCustomerOrderNumber();
                    final String trackingNumber = getTrackingNumberResponseItem.getTrackingNumber();
                    final TrackingNumberStatusEnum trackingNumberStatusEnum = IEnumConvert.valueOf(getTrackingNumberResponseItem.getStatus(), TrackingNumberStatusEnum.class);
                    OrderEntity matchingOrder = orderEntityList.stream()
                            .filter(order -> customerOrderNumber.equals(order.getSysOrderId()))
                            .findFirst()
                            .orElse(null);
                    if (matchingOrder != null) {
                        switch (trackingNumberStatusEnum) {
                            case SUCCESS:
                                // 成功处理逻辑
                                matchingOrder.setTrackingNumber(trackingNumber);
                                break;

                            case IN_PROGRESS:
                                // 跟踪号生成中的处理逻辑
                                break;

                            case NO_GENERATION_REQUIRED:
                                // 无需生成跟踪号的处理逻辑
                                matchingOrder.setTrackingNumber("null");
                                break;

                            case FAILURE:
                                // 生成失败的处理逻辑
                                matchingOrder.setTrackingNumber("null");
                                break;

                            default:
                                // 其他情况的处理逻辑
                                break;
                        }
                    }
                }
            }
        }
        orderService.batchUpdateTrackingNumById(orderEntityList);
    }

    // 云途getTrackingNumber批量接口CustomerOrderNumber最多支持30条数据
    public List<String> generateSysOrderIdStrings(List<OrderEntity> orderEntityList) {
        if (orderEntityList == null || orderEntityList.isEmpty()) {
            return new ArrayList<>();  // 返回空列表
        }
        // 提取所有SysOrderId
        List<String> sysOrderIds = orderEntityList.stream()
                .map(OrderEntity::getSysOrderId)
                .collect(Collectors.toList());

        List<String> result = new ArrayList<>();
        StringBuilder currentString = new StringBuilder();
        int count = 0;  // 计数器，记录当前字符串包含的SysOrderId数量

        for (String sysOrderId : sysOrderIds) {
            // 检查加入当前sysOrderId后是否会超过30个
            if (count >= 30) {
                // 添加到结果集并开始一个新的字符串
                result.add(currentString.toString());
                currentString = new StringBuilder();
                count = 0;
            }
            // 添加sysOrderId并用逗号连接
            if (currentString.length() > 0) {
                currentString.append(",");
            }
            currentString.append(sysOrderId);
            count++;
        }

        // 添加最后一个字符串
        if (currentString.length() > 0) {
            result.add(currentString.toString());
        }

        return result;
    }

}
